{include 'header.tpl'}
<div class="contant">
    <div class="header">
        <div class="header_s">
            <span class="back"><a href="javascript:history.go(-1);"><i class="iconfont fan">&#xe679;</i></a></span>
            <span class="title">选择收货地址</span>
            <span class="add_ads"><a href="/add/in" style="color: white;">新增地址</a></span>
            <div class="clear"></div>
            <div class="search">
                <div class="region">长沙市<i></i></div>
                <div class="sr_region"><input type="search" id="search" placeholder="请输入您的收货地址" class=""></div>
            </div>
        </div>
    </div>
    <div class="ads_list_by">
        <div class="location" id="locations">
            <i class="iconfont locations"></i><span>定位当前位置</span>
        </div>
    </div>

    <div class="loc">
        <div class="loc_tlt">附近地址</div>
        <div class="loc_list">
            <ul id="wordMap">
                {*<li>加载中...</li>*}
                {*<li><a>麓谷企业广场C4</a></li>
                <li><a>麓谷企业广场C4</a></li>
                <li><a>麓谷企业广场C4</a></li>*}
            </ul>
        </div>
    </div>
</div>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="application/javascript" src='http://api.map.baidu.com/api?v=2.0&ak=pRtqXqnajTytAzWDL3HOnPRK'></script>
<script>
    var refer = '{$refer}' || '/';
</script>
{literal}
<script>
    //delCookie('_base');
    var isQuery = true;
    var mapRes = {};
    var mapOpt = {};
    var base = getCookie('_base') || {};
    var local = new BMap.LocalSearch('长沙', {
        pageCapacity: 20,
        onSearchComplete: function(result){
            isQuery = true;
            $("#wordMap").html('');
            var arr = [];
            if (local.getStatus() == BMAP_STATUS_SUCCESS) {
                for (var i = 0; i < result.getCurrentNumPois(); i++) {
                    var item = result.getPoi(i);
                    if (!item.title || (item.tags && !item.tags.length) || !item.province || !item.address || !item.point.lng || /市$/.test(item.title) || /省$/.test(item.title) || /^朝阳区$/.test(item.title)) {
                        continue
                    }
                    var isTag = true;
                    item.tags = item.tags ? item.tags : [];
                    for (var j = 0; j < item.tags.length; j++) {
                        var tag = item.tags[j];
                        if (tag == '区县' || tag == '行政地标' || tag == '地级市' || tag == '名称标注类' || tag == '公交车站') {
                            isTag = false;
                            break
                        }
                    }
                    if (!isTag) {
                        continue;
                    }
                    var list = $("<li><a>"+item.title+"</a></li>");
                    list.data("latlng", item.point.lat + ',' + item.point.lng);
                    list.data("city", item.city);
                    list.data("province", item.province);
                    list.data("address", item.address);
                    list.data("title", item.title);
                    list.bind('click',function(){
                        base.zb = $(this).data('latlng');
                        base.address = $(this).data('address');
                        base.city =$(this).data('city');
                        base.province =$(this).data('province');
                        base.sematic = $(this).data('title');
                        setCookie('_base',base,2);
                        window.location.href = refer;
                    });
                    // 关键字加红色
                    var re = new RegExp(result.keyword);
                    item.title = item.title.replace(re, '<b>' + result.keyword + '</b>');

                    arr.push(list[0]);
                }
                // 排序
                arr = fieldsSort(arr, '+dis', "");
                for (var x in arr) {
                    var items = arr[x];
                    $(items).appendTo($("#wordMap"));
                }
            }
        }
    });

    function fail() {
        $('#locations span').text('定位失败');
    }
    $(function () {
        // 定义搜索类
        function get_city_name_by_geo(js_api_list,callback,fail){
            $('#locations span').text('自动定位中');
            $.get('/location/service',function (res) {
                // 初始化微信接口
                wx.config({
                    debug: false,
                    appId: res.data.appid,
                    timestamp: res.data.timestamp,
                    nonceStr: res.data.nonceStr,
                    signature: res.data.signature,
                    jsApiList: js_api_list || ["getLocation"]
                });

                wx.ready(function () {
                    wx.getLocation({
                        type: "wgs84",
                        success: function (wx_res) {
                            if (wx_res.errMsg == "getLocation:ok") {
                                // 通过百度api转换当前经纬度坐标
                                $.ajax({
                                    url: "http://api.map.baidu.com/geocoder/v2/?",
                                    type: "get",
                                    data: {
                                        coordtype: 'wgs84ll',
                                        location: wx_res.latitude + "," + wx_res.longitude,
                                        ak: 'pRtqXqnajTytAzWDL3HOnPRK',
                                        //callback: 'renderReverse',
                                        output: 'json',
                                        pois: 1
                                    },
                                    async: false,
                                    dataType: "jsonp",
                                    success: function (geo_res) {
                                        var option = {};
                                        if (geo_res.status != 0) {
                                            //alert('转换失败!');
                                            return;
                                        }
                                        callback(geo_res.result);
                                    }
                                });
                            }else{
                                fail();
                            }
                        }
                    });
                });
            });
        }

        // 定义周边POI检索类
        var POI = new BMap.Geocoder();

        function location() {
            get_city_name_by_geo('',function (_res) {
                var option = {};
                option.address = _res.pois.length == 0 ? _res.formatted_address : _res.sematic_description;
                option.latlng = _res.location.lng + ',' + _res.location.lat;
                base.zb = option.latlng;
                base.sematic = _res.sematic_description;
                base.address = _res.formatted_address;
                base.city = _res.addressComponent.city;
                base.province = _res.addressComponent.province;
                setCookie('_base',base,2);
                mapRes = _res;
                mapOpt = option;
                window.location.href = refer;
                getPois(option.latlng);
            });
        }
        
        if($.isEmptyObject(base)){
            location();
        }

        $('#locations').click(function () {
            location();
        });

        $("#search").on("input",function() {
            if(!isQuery || $(this).val() == "" ) return;
            $("#wordMap li").remove();
            isQuery = false;
            local.search($("#search").val().trim(),{forceLocal: true});
        });

        // 搜索框聚焦
        $(document).on('focus','#search',function(){
            $(this).trigger("input");
        });

        //console.log(Date.now());
        if(base.zb)
            getPois(base.zb);

        function getPois(pos){
            var posopt =  pos.split(',');
            //var point = new BMap.Point(112.89211,28.214494);
            var point = new BMap.Point(posopt[0],posopt[1]);
            POI.getLocation(point,function(res){
                base.address = res.address;
                base.city = res.addressComponents.city;
                base.province = res.addressComponents.province;

                setCookie('_base',base,2);
                $("#wordMap").html('');
                var arr = [];
                for(var i in res.surroundingPois){
                    var item = res.surroundingPois[i];
                    if (!item.title || !item.address) {
                        continue;
                    }
                    var list = $("<li><a>"+item.title+"</a></li>");
                    list.data("latlng", item.point.lng + ',' + item.point.lat);
                    list.data("city", res.addressComponents.city);
                    list.data("province", res.addressComponents.province);
                    list.data("address", res.address);
                    list.data("title", item.title);
                    arr.push(list[0]);
                }
                // 排序
                arr = fieldsSort(arr, '+dis', "")
                for (var x in arr) {
                    var items = arr[x];
                    $(items).appendTo($("#wordMap"))
                }
            },{
                poiRadius : 3000,
                numPois : 10
            });
        }
    });

    // 计算距离
    function count(lat_a, lng_a, lat_b, lng_b) {
        var pk = 180 / 3.14169;
        var a1 = lat_a / pk;
        var a2 = lng_a / pk;
        var b1 = lat_b / pk;
        var b2 = lng_b / pk;
        var t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
        var t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
        var t3 = Math.sin(a1) * Math.sin(b1);
        var tt = Math.acos(t1 + t2 + t3);
        return 6366000 * tt
    }
    // 微信分享
    var wx_config = {
        tag: '定位'
    };

    // 排序
    var fieldsSort = function(arr,field1,field2) {
        var char1=field1.charAt(0),
            char2=field1.charAt(0),
            dir1=char1==="-"?-1:1,
            dir2=char2==="-"?-1:1;
        if(char1==="-"||char1==="+")field1=field1.substr(1);
        if(char2==="-"||char2==="+")field2=field2.substr(1);
        arr.sort(function(a,b){
            return a[field1]===b[field1]?(a[field2]-b[field2])*dir2:(a[field1]-b[field1])*dir1;
        });
        return arr;
    }
</script>
{/literal}
{include 'footer.tpl'}